package com.fary.core.io.support;

import com.fary.core.io.InputStreamSource;
import com.fary.core.io.Resource;
import com.fary.util.Assert;


import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

public class EncodedResource implements InputStreamSource {

    private final Resource resource;

    private final String encoding;

    private final Charset charset;

    public EncodedResource(Resource resource) {
        this(resource, null, null);
    }

    public EncodedResource(Resource resource, String encoding) {
        this(resource, encoding, null);
    }


    private EncodedResource(Resource resource, String encoding, Charset charset) {
        super();
        Assert.notNull(resource, "Resource must not be null");
        this.resource = resource;
        this.encoding = encoding;
        this.charset = charset;
    }

    public final Resource getResource() {
        return this.resource;
    }

    public final String getEncoding() {
        return this.encoding;
    }


    public boolean requiresReader() {
        return (this.encoding != null || this.charset != null);
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return this.resource.getInputStream();
    }

    public Reader getReader() throws IOException {
        if (this.charset != null) {
            return new InputStreamReader(this.resource.getInputStream(), this.charset);
        } else if (this.encoding != null) {
            return new InputStreamReader(this.resource.getInputStream(), this.encoding);
        } else {
            return new InputStreamReader(this.resource.getInputStream());
        }
    }
}